package com.lyn.solitude.plugin

import com.android.build.api.instrumentation.AsmClassVisitorFactory
import com.android.build.api.instrumentation.ClassContext
import com.android.build.api.instrumentation.ClassData
import com.android.build.api.instrumentation.InstrumentationParameters
import com.android.tools.r8.internal.mv
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.FieldVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import java.io.File
import java.io.FileOutputStream
import java.io.FileWriter

/**
 *
 * @author longyn 2024/05/13
 * @version 1.0.0
 */
abstract class SetPluginClassNameVisitorFactory
    : AsmClassVisitorFactory<InstrumentationParameters.None> {


    override fun isInstrumentable(classData: ClassData): Boolean {
        return classData.classAnnotations.contains("com.lyn.solitude.api.annotation.MainPlugin")
    }

    override fun createClassVisitor(
        classContext: ClassContext,
        nextClassVisitor: ClassVisitor
    ): ClassVisitor {
        val file = File(FileUtil.buildPath + "com.lyn.solitude.plugin").apply {
            if (!this.exists()) {
                mkdirs()
            }
        }
        val file2 = File(file, "PluginBuildConfig.java").apply {
            if (!this.exists()) {
                createNewFile()
            }
        }
        val sb = StringBuilder()
        sb.append("package com.lyn.solitude.plugin;").append("\n")
        sb.append("\n")
        sb.append("public class PluginBuildConfig ").append("{")
        sb.append("\n")
        sb.append("    public static final String MAIN_PLUGIN_CLASS_NAME = ")
            .append("\"" + classContext.currentClassData.className + "\"").append(";").append("\n")
        sb.append("}")
        FileWriter(file2, false).apply {
            write(sb.toString())
            flush()
            close()
        }
        return object : ClassVisitor(Opcodes.ASM9, nextClassVisitor) {
        }
    }
}